from time import sleep

from selenium import webdriver

import tools.addUser as Au
import tools.buyTickets as Buy
import tools.readcsv as Csv
import tools.readjson as Json
from tools.login import logout, login, verificationCode
from tools.selector import select

# 功能模块间隔时间
wait_time = 0

try:
    # 读取文件
    try:
        user = Json.read("config/user.json")
    except FileNotFoundError as e:
        print("没有找到登录配置文件，请去config创建user.json")
        exit()
    add_user = Csv.read("config/adduser.csv")
    data = Csv.read("config/data.csv")
    ticket = Json.read("config/ticket.json")

    # 避免webdriver检测
    options = webdriver.ChromeOptions()
    options.add_argument('--disable-blink-features=AutomationControlled')
    options.add_experimental_option('excludeSwitches', ['enable-automation'])
    driver = webdriver.Chrome(options=options)

    # 设置隐式等待为5秒
    driver.implicitly_wait(5)

    # 打开12306网站
    driver.get("https://www.12306.cn")

    # 设置浏览器全屏
    driver.maximize_window()

    # 点击登录
    select(driver, data[0]).click()

    # 登录模块
    login(driver, user, data)
    sleep(wait_time)

    # 验证码
    verificationCode(driver, data)
    sleep(wait_time)

    # 点击疫情确认按钮
    select(driver, data[7]).click()

    # 添加联系人模块
    Au.addUser(driver, add_user, data)
    sleep(wait_time)

    # 添加购票模块
    Buy.vote(driver, user, ticket, data)
    sleep(wait_time)

    # 登出
    logout(driver, data)

except Exception as e:
    print(e)
    driver.quit()
finally:
    # 退出浏览器
    sleep(wait_time)
    print("关闭浏览器")